package com.log4jviewer.ui.preferences.filters;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;

import com.log4jviewer.filters.FilterConstants;
import com.log4jviewer.filters.FilterItemModel;

/**
 * Create possibility modify the Include cell in Rules Table
 * 
 * @author <a href="mailto:solid.danil@gmail.com">Daniil Lopatin</a>
 */
public class RulesIncludeCellEditor extends EditingSupport {

    private final TableViewer tableViewer;

    public RulesIncludeCellEditor(final TableViewer tableViewer) {
        super(tableViewer);
        this.tableViewer = tableViewer;
    }

    @Override
    protected CellEditor getCellEditor(final Object element) {
        return new ComboBoxCellEditor(tableViewer.getTable(), FilterConstants.MATCH_PATTERN_INCLUDE, SWT.READ_ONLY);
    }

    @Override
    protected boolean canEdit(final Object element) {
        return true;
    }

    @Override
    protected Object getValue(final Object element) {
        FilterItemModel filterItemModel = (FilterItemModel) element;
        String includeItem;

        if (filterItemModel.isEnabled()) {
            includeItem = FilterConstants.INCLUDE;
        } else {
            includeItem = FilterConstants.EXCLUDE;
        }
        int includeIndex = 0;

        for (int i = 0; i < FilterConstants.MATCH_PATTERN_INCLUDE.length; i++) {
            if (includeItem.equals(FilterConstants.MATCH_PATTERN_INCLUDE[i])) {
                includeIndex = i;
                break;
            }
        }
        return includeIndex;
    }

    @Override
    protected void setValue(final Object element, final Object value) {
        FilterItemModel filterItemModel = (FilterItemModel) element;

        if ((FilterConstants.MATCH_PATTERN_INCLUDE[(Integer) value]).equals(FilterConstants.INCLUDE)) {
            filterItemModel.setInclude(true);
        } else {
            filterItemModel.setInclude(false);
        }
        tableViewer.update(element, null);
    }

}
